package net.wicp.tams.common.apiext.yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Reader;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.reader.UnicodeReader;

import com.alibaba.fastjson.JSONObject;

import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.json.JSONUtil;

public abstract class YamlUtil {
	/****
	 * 检查yaml是否合法
	 * 
	 * @param fileInputStream
	 *            文件的流
	 * @return 检查的结果
	 */
	@SuppressWarnings({ "unused" })
	public static Result isOk(FileInputStream fileInputStream) {
		Yaml yaml = new Yaml(new StrictMapAppenderConstructor());
		Result retobj = null;
		try {
			Reader reader = new UnicodeReader(fileInputStream);
			for (Object obj : yaml.loadAll(reader)) {
			}
			retobj = Result.getSuc();
		} catch (Exception e) {
			retobj = Result.getError(e.getMessage());
		}
		return retobj;
	}

	public static Result isOk(String fileName) {
		FileInputStream inputstream;
		try {
			inputstream = new FileInputStream(fileName);
		} catch (FileNotFoundException e) {
			return Result.getError("文件不存在");
		}
		return isOk(inputstream);
	}

	@SuppressWarnings("rawtypes")
	public static JSONObject readYaml(FileInputStream fileInputStream) {
		Yaml yaml = new Yaml();
		Map map = (Map) yaml.load(fileInputStream);
		JSONObject json = JSONObject.parseObject(JSONUtil.getJsonForMap(map));
		return json;
	}

	public static JSONObject readYamlStr(String yamlstr) {
		Yaml yaml = new Yaml();
		Map map = (Map) yaml.load(yamlstr);
		JSONObject json = JSONObject.parseObject(JSONUtil.getJsonForMap(map));
		return json;
	}

	public static JSONObject readYaml(String filePath) {
		FileInputStream inputstream;
		try {
			inputstream = new FileInputStream(filePath);
		} catch (FileNotFoundException e) {
			throw new IllegalArgumentException("file not exit");
		}
		return readYaml(inputstream);
	}

}
